﻿#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "chatsocket.h"
#include "freindwidget.h"

MainWidget* MainWidget::m_pMain;
MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);
    m_pTreeWidget = nullptr;
    m_pMain = nullptr;
    setShadow();
    loadImg();
    ui->treeWidget->setIndentation(0);
    ui->lineEdit->setEnabled(true);
    ui->lineEdit->setFocus();
    connect(ui->treeWidget_2,&QTreeWidget::itemDoubleClicked,this,&MainWidget::on_treeWidget_itemDoubleClicked);
}

MainWidget::~MainWidget()
{
    delete ui;
}

MainWidget *MainWidget::getInstance()
{
    if(m_pMain == nullptr)
        m_pMain = new MainWidget;
    return m_pMain;
}

void MainWidget::init(const QString& id)
{
    //设置头像，昵称，个性签名
    QString path = QCoreApplication::applicationDirPath();
    QString headurl = ChatDB::getInstance()->getImgUrl(id);
    QString style = QString("min-width:  80px;max-width:  80px;min-height: 80px;max-height: 80px;border-radius: 40px;border-width: 1 1 1 1;border-image: url(%1) 0 0 0 0 stretch strectch;").arg(headurl);
    ui->btn_head->setStyleSheet(style);
    QString nickname = ChatDB::getInstance()->getNickName(id);
    QString signatrue = ChatDB::getInstance()->getSignatrue(id);
    ui->label_nickname->setText(nickname);
    ui->label_nickname->setStyleSheet("font: 75 12pt \"微软雅黑\";");
    ui->label_signatrue->setText(signatrue);

    //初始化树控件 我的好友我的群聊
    QTreeWidgetItem* top1 = new QTreeWidgetItem(QStringList()<<"我的好友");
    ui->treeWidget->setHeaderHidden(true);
    ui->treeWidget->setColumnCount(1);
    ui->treeWidget->addTopLevelItem(top1);
    ui->treeWidget->setIconSize(QSize(50,50));

    QTreeWidgetItem* top2 = new QTreeWidgetItem(QStringList()<<"我的群聊");
    ui->treeWidget_2->setHeaderHidden(true);
    ui->treeWidget_2->setColumnCount(1);
    ui->treeWidget_2->addTopLevelItem(top2);
    ui->treeWidget_2->setIconSize(QSize(50,50));

}

void MainWidget::loadFriendAndLoadGroup(const QList<UserInfo>& uinfo,const QList<groupinfo>& ginfo)
{
    QList<QTreeWidgetItem *> list = ui->treeWidget->topLevelItem(0)->takeChildren();
    QList<QTreeWidgetItem *> list2 = ui->treeWidget_2->topLevelItem(0)->takeChildren();
    for(auto obj : list)
    {
        if(obj)
            delete obj;
    }
    for(auto obj : list2)
    {
        if(obj)
            delete obj;
    }
    //加载好友信息
    for(auto obj : uinfo)
    {
        int online = obj.online;
        QString usertext =  QString(obj.nickname) + "("+obj.id+")";
        QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<usertext);
        QString imgpath = obj.headurl;
        QFile file;
        file.setFileName(imgpath);
        if(!file.open(QIODevice::ReadOnly))//若不存在头像 则使用默认头像
        {
            imgpath = "res/Icon/joker2.png";
        }
        QIcon icon1(imgpath);
        item->setIcon(0,icon1);
        if(online == 0)
        {
            item->setBackground(0,QColor(215,215,215));
        }
        ui->treeWidget->topLevelItem(0)->addChild(item);
    }
    ui->treeWidget->expandItem(ui->treeWidget->topLevelItem(0));
    //加载群聊信息
    for(auto obj : ginfo)
    {
        QString text = QString(obj.gname) + "("+ QString(obj.gid) + ")";
        QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<text);
        QString imgpath = obj.gimg;
        QFile file;
        file.setFileName(imgpath);
        if(!file.open(QIODevice::ReadOnly))//若不存在头像 则使用默认头像
        {
            imgpath = "res/Icon/joker2.png";
        }
        QIcon icon(imgpath);
        item->setIcon(0,icon);
        item->setBackground(0,QColor(255,255,255));
        ui->treeWidget_2->topLevelItem(0)->addChild(item);
    }
    ui->treeWidget_2->expandItem(ui->treeWidget_2->topLevelItem(0));
}

void MainWidget::changeUserStatus(QString id, bool status)
{
    QList<QTreeWidgetItem*> list = ui->treeWidget->findItems(id,Qt::MatchContains|Qt::MatchRecursive);
    if(status && list.size())
    {
        list[0]->setBackground(0,QColor(255,255,255));
    }
    else if(list.size() && !status)
    {
        list[0]->setBackground(0,QColor(215,215,215));
    }
}

bool MainWidget::queryIsFriend(QString id)
{
    QList<QTreeWidgetItem *> friendlist = ui->treeWidget->findItems(id,Qt::MatchContains|Qt::MatchRecursive);
    return friendlist.size() == 0;
}


void MainWidget::mousePressEvent(QMouseEvent *event)
{
    if(event->buttons() == Qt::LeftButton)
    {
        isPressedWidget = true; // 当前鼠标按下的是QWidget而非界面上布局的其它控件
        last_point = event->globalPos();
    }
}

void MainWidget::mouseMoveEvent(QMouseEvent *event)
{
    if(this->isMaximized())
        return;
    if (isPressedWidget)
    {
        int dx = event->globalX() - last_point.x();
        int dy = event->globalY() - last_point.y();
        last_point = event->globalPos();
        move(x()+dx, y()+dy);
    }
}

void MainWidget::mouseReleaseEvent(QMouseEvent *event)
{
    int dx = event->globalX() - last_point.x();
    int dy = event->globalY() - last_point.y();
    move(x()+dx, y()+dy);
    isPressedWidget = false; // 鼠标松开时，置为false
}

void MainWidget::setShadow()
{
    //设置无边框
    setWindowFlags(Qt::FramelessWindowHint);
    //设置窗体透明
    setAttribute(Qt::WA_TranslucentBackground, true);
    QGraphicsDropShadowEffect *shadow=new QGraphicsDropShadowEffect();
    shadow->setBlurRadius(15);//设置圆角半径
    shadow->setColor(QColor(0,0,0));//设置边框颜色
    shadow->setOffset(0,0);
    ui->CWidget->setStyleSheet("background-color:white");
    ui->CWidget->setGraphicsEffect(shadow);
}

void MainWidget::loadImg()
{
    QIcon iconSerch = QIcon("res/Icon/search.png");
    QIcon iconApp = QIcon("res/Icon/app.png");
    QIcon iconAddFriend = QIcon("res/Icon/addfriend.png");
    QIcon iconSetting = QIcon("res/Icon/setting.png");
    ui->toolButton->setIcon(iconSerch);
    ui->toolButton->setIconSize(QSize(30,35));
    ui->label_icon->setPixmap(QPixmap("res/Icon/joker2.png"));
    ui->tool_app->setIcon(iconApp);
    ui->tool_app->setIconSize(QSize(40,40));
    ui->tool_setting->setIcon(iconSetting);
    ui->tool_setting->setIconSize(QSize(40,40));
    ui->tool_addfriend->setIcon(iconAddFriend);
    ui->tool_addfriend->setIconSize(QSize(40,40));
}

void MainWidget::on_btn_close_clicked()
{
    close();
}

void MainWidget::on_btn_min_clicked()
{
    showMinimized();
}

void MainWidget::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)//添加双击事情，弹出聊天对话框
{
    if(item->parent()==nullptr)//若点击的为顶层控件  则直接返回
    {
        return;
    }
    for(auto obj : ChatSocket::getInstance()->m_chatList)
    {
        if(obj->getWinName() == item->text(0))
        {
            obj->raise();
            obj->show();
            return;
        }
    }
    for(auto obj : ChatSocket::getInstance()->m_groupList)
    {
        if(obj->getWinName() == item->text(0))
        {
            obj->raise();
            obj->show();
            return;
        }
    }
    QList<QTreeWidgetItem *> friendlist = ui->treeWidget->findItems(item->text(0),Qt::MatchContains|Qt::MatchRecursive);
    QList<QTreeWidgetItem *> grouplist = ui->treeWidget_2->findItems(item->text(0),Qt::MatchContains|Qt::MatchRecursive);
    if(friendlist.size())
    {
        ChatWidget* cw = new ChatWidget;
        cw->setWinName(item->text(0));
        cw->show();
        ChatSocket::getInstance()->m_chatList.append(cw);
        //查找有无与其的聊天记录
        //查找有无聊天记录
        QString str(item->text(0));
        int i = str.indexOf('(');
        str =str.replace(")","");
        str = str.mid(i+1);
        QString path = QCoreApplication::applicationDirPath();
        QString uid = Widget::getInstance()->getID();
        QString filename = QString("%1/%2/%3-%4.txt").arg(path).arg(uid).arg(uid).arg(str);
        QFile file(filename);
        if(file.exists())
        {
            if(!file.open(QIODevice::ReadOnly))
            {
                QMessageBox::warning(this,"警告","打开文件失败");
                return;
            }
            char info[1024];
            char info2[1024];
            while(!file.atEnd())
            {
                memset(info,0,1024);
                memset(info2,0,1024);
                file.readLine(info,1024);
                QString msg2="";
                while(1)
                {
                    file.readLine(info2,1024);
                    msg2 += QString(info2);
                    QString content(info2);
                    if(content.endsWith("わ\r\n"))
                    {
                        break;
                    }
                }
                QString msg = QString(info)+"&" + msg2;
                cw->restoreChatLog(msg);
            }
            file.close();
        }
    }
    else if(grouplist.size())//群聊
    {
        GroupWidget* gw = new GroupWidget;
        gw->setWinName(item->text(0));
        gw->show();
        ChatSocket::getInstance()->m_groupList.append(gw);
    }
}

void MainWidget::on_tool_addfriend_clicked()
{
    FreindWidget* fw = new FreindWidget;
    fw->show();
}

void MainWidget::on_lineEdit_textChanged(const QString &arg1)//搜索好友
{
    if(arg1.size() == 0)
    {
        m_pTreeWidget->hide();
        QList<QTreeWidgetItem *> list = m_pTreeWidget->topLevelItem(0)->takeChildren();
        for(auto obj : list)
            delete obj;
        return;
    }
    if(m_pTreeWidget == nullptr)
    {
        m_pTreeWidget = new QTreeWidget(ui->CWidget);
        m_pTreeWidget->setIndentation(20);
        m_pTreeWidget->resize(385,600);
        m_pTreeWidget->move(0,150);
        QTreeWidgetItem* top1 = new QTreeWidgetItem(QStringList()<<"搜索结果");
        m_pTreeWidget->setHeaderHidden(true);
        m_pTreeWidget->setColumnCount(1);
        m_pTreeWidget->addTopLevelItem(top1);
        m_pTreeWidget->setIconSize(QSize(50,50));
        connect(m_pTreeWidget,&QTreeWidget::itemDoubleClicked,this,&MainWidget::on_treeWidget_itemDoubleClicked);
    }
    QList<QTreeWidgetItem*> list = ui->treeWidget->findItems(arg1,Qt::MatchContains|Qt::MatchRecursive);
    QList<QTreeWidgetItem*> list2 = ui->treeWidget_2->findItems(arg1,Qt::MatchContains|Qt::MatchRecursive);
    for(auto obj : list)
    {
        QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<obj->text(0));
        QIcon icon(obj->icon(0));
        item->setIcon(0,icon);
        item->setBackground(0,QColor(255,255,255));
        m_pTreeWidget->topLevelItem(0)->addChild(item);
    }
    for(auto obj : list2)
    {
        QTreeWidgetItem* item = new QTreeWidgetItem(QStringList()<<obj->text(0));
        QIcon icon(obj->icon(0));
        item->setIcon(0,icon);
        item->setBackground(0,QColor(255,255,255));
        m_pTreeWidget->topLevelItem(0)->addChild(item);
    }
    m_pTreeWidget->expandAll();
    m_pTreeWidget->show();
}
